
let user = null, //用户
	partner = null, //伴侣
	partnerConfig = null, //绑定后伴侣信息配置
	inviter = null, //邀请人
	reqTime = 0

/**
 * 设置用户信息
 * @param {Object} user
 */
function setUser(user) {
	if (!this.user) {
		this.user = user
	} else {
		Object.assign(this.user, user)
	}
	uni.setStorage({
		key: 'user',
		data: this.user
	});
}
/**
 * 获取用户信息
 */
function getUser() {
	return this.user
}
/**
 * 设置伴侣信息
 * @param {Object} partner
 */
function setPartner(partner) {
	if (!this.partner || !partner) {
		this.partner = partner
	} else {
		Object.assign(this.partner, partner)
	}
	uni.setStorage({
		key: 'partner',
		data: this.partner
	});
}
/**
 * 获取伴侣信息
 */
function getPartner() {
	return this.partner
}
/**
 * 设置绑定伴侣配置信息
 * @param {Object} config
 */
function setPartnerConfig(config) {
	if (!this.partnerConfig || !config) {
		this.partnerConfig = config
	} else {
		Object.assign(this.partnerConfig, config)
	}
	uni.setStorage({
		key: 'partnerConfig',
		data: this.partnerConfig
	});
}
/**
 * 获取绑定伴侣配置信息
 */
function getPartnerConfig() {
	return this.partnerConfig
}

/**
 * 更新user对象
 */
async function updateCacheByUser() {
	const newTime = new Date().getTime()
	if (this.user && newTime - this.reqTime > 60 * 1000) {
		this.reqTime = newTime;
		const db = uniCloud.database(),
			res = await db.collection('user').doc(this.user._id).get({
				getOne: true
			})
		this.user = res.result.data
		uni.setStorage({
			key: 'user',
			data: this.user
		});
		if (this.user.partnerId) {
			const partner = db.collection('user').doc(this.user.partnerId).getTemp({
					getOne: true
				}),
				config = db.collection('partner_config').doc(this.user.configId).getTemp({
					getOne: true
				}),
				multiSendRes = await db.multiSend(partner, config)

			this.partner = multiSendRes.result.dataList[0].data
			this.partnerConfig = multiSendRes.result.dataList[1].data
			uni.setStorage({
				key: 'partner',
				data: this.partner
			});
			uni.setStorage({
				key: 'partner',
				data: this.partnerConfig
			});
		}
		return true
	}
	return false
}

/**
 * 通过openId用户登录/注册
 * @param {String} openId
 */
async function onLogin(openId) {
	// 通过openid查找用户
	const db = uniCloud.database(),
		userRes = await db.collection('user').where({
			openId: openId
		}).get({
			getOne: true
		}).catch((err) => {
			uni.$u.toast('操作异常');
			throw err
		})
	let data = userRes.result.data
	if (!data) {
		//创建用户
		const addUserRes = await db.collection('user')
			.add({
				openId: openId
			}).catch((err) => {
				uni.$u.toast('用户创建失败')
				throw err
			});
		const userId = addUserRes.result.id
		this.onBindInviter(userId)
		this.setUser({
			_id: userId,
			openId: openId,
			partnerId: null,
			configId: null,
			nickName: null,
			gender: null,
			birthYear: null,
			integral: null,
			avatar: null,
			state: '0'
		})
		return 0;
	}

	this.setUser(data)
	if (data.state > 0) {
		const partnerRes = await db.collection('user')
			.doc(data.partnerId).get({
				getOne: true
			}).catch((err) => {
				uni.$u.toast('网络异常');
				throw err
			})
		this.setPartner(partnerRes.result.data)
	} else {
		await this.onBindInviter(data._id)
	}
	db.collection('user')
		.doc(data._id).update({
			loginTime: uni.$u.timeFormat(new Date().getTime(), 'yyyy年mm月dd日 hh时MM分ss秒')
		})
	return 1;
}

async function onBindInviter(userId) {
	if (this.inviterId && userId != this.inviterId) {
		const res = await uniCloud.database().collection('user')
			.doc(this.inviterId).get({
				getOne: true
			}).catch((err) => {
				uni.$u.toast('网络异常');
				throw err
			})
		const data = res.result.data
		if (data.state == 0) {
			this.inviter = data
		}
	}
}

function getYMDHMS(timestamp) {
	let time = new Date(timestamp)
	let year = time.getFullYear()
	const month = (time.getMonth() + 1).toString().padStart(2, '0')
	const date = (time.getDate()).toString().padStart(2, '0')
	const hours = (time.getHours()).toString().padStart(2, '0')
	const minute = (time.getMinutes()).toString().padStart(2, '0')
	const second = (time.getSeconds()).toString().padStart(2, '0')

	return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
}

export default {
	inviter,

	getUser,
	getPartner,
	getPartnerConfig,
	setUser,
	setPartner,
	setPartnerConfig,

	onLogin,
	updateCacheByUser,
	getYMDHMS,
}
